<?php
/**
 * @Author: xuzhiyi
 * @Date:   2016-02-16 20:57:17
 * @Last Modified by:   xuzhiyi
 * @Last Modified time: 2016-02-22 09:18:27
 * ------------------------------------------------ *
 * 文章分类                                         *
 * ------------------------------------------------ */
namespace Admin\Model;

class ArticleCatsModel extends CommonModel{
	/* 改变状态
	 *--------------------------*/
	public function editStatus(){
	 	if(I('catId',0)==0) return false;
	 	$a = M('article_cats');
	 	$data['catFlag'] = (I('catFlag')==1)?1:0;
	 	$rs = $a->where("catId=".(int)I('catId',0))->save($data);
	    if(false !== $rs){
			return true;
		}
	 	return false;
	}


	/* 添加文章
	 *--------------------------*/
	 public function addArticleCats(){
		$data = array();
		$data["parentId"] = I("parentId");
		$data["catName"] = I("catName");
		$data["catFlag"] = 1;
	    if($this->checkEmpty($data)){
	    	$data["catSort"] = I("catSort");
	    	$data["catType"] = I("catType");
			$u = M('article_cats');
			$rs = $u->add($data);
			if(false !== $rs){
				return true;
			}
		}
		return false;
	}

	//删除文章
	 public function delArticleCats(){
	 	$catId = (int)I('catId');
	 	$a = M('article_cats');
	 	$check=$a->where("parentId=".$catId)->getField('catId');
	 	if($check){//有无子类
	 		return "other";
	 	}
	 	$data['catFlag']=-1;
	    $rs = $a->where("catId=".$catId)->save($data);
		if(false !== $rs){
			return true;
		}
		return false;
	 }

	 
	 /* 修改文章
	 *--------------------------*/
	 public function editArticleCats(){

	 	$catId = (int)I("catId",0);
		$data = array();
		$data["parentId"] = I("parentId");
		$data["catName"] = I("catName");

	    if($this->checkEmpty($data)){
	    	$data["catSort"] = I("catSort");
	    	$data["catType"] = I("catType");
			$rs = M('article_cats')->where("catId=".$catId)->save($data);
			if(false !== $rs){
				return true;
			}
		}
		return false;
	}

	/* 获得分类列表
	* --------------------*/
	public function getArticleCats(){
		$a=M('article_cats');
		$rs = $a->where('catFlag!=-1')->order('parentId asc')->select();
		$result = $this->tree($rs);
		$output['data'] = $result;
		return $output;
	}

	//格式化数据
	public function tree(&$data,$pid = 0, $count = 0) {
		if(!isset($data['old'])){
	        $data=array('new'=>array(),'old'=>$data);
	    }
	    foreach ($data['old'] as $k => $v){
	        if($v['parentId']==$pid){
	            $v['count'] = '';
	            if($count>0)
	            	$v['count'] = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $count).'├── ';
	            $data['new'][]=$v;
	            unset($data['old'][$k]);
	            $this->tree($data,$v['catId'],$count+1);
	        } 
	    }
	    return $data['new'] ;
	}
 }